package online.sixfish.doubao.controller;

import online.sixfish.common.api.ApiResult;
import online.sixfish.common.dto.PageDTO;
import online.sixfish.doubao.event.CoursewareDownloadEvent;
import online.sixfish.doubao.model.entity.Courseware;
import online.sixfish.doubao.service.CoursewareService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/courseware")
public class CoursewareController {
    @Resource
    CoursewareService coursewareService;
    @Resource
    ApplicationEventPublisher eventPublisher;

    @GetMapping("/list")
    public ApiResult list(@RequestParam(required = false) String type,
                          @RequestParam(required = false) String name,
                          @RequestParam Integer pageNum,
                          @RequestParam Integer pageSize) {
        PageDTO pageDTO = coursewareService.list(type, name, pageNum, pageSize);
        return ApiResult.success(pageDTO);
    }

    @PostMapping("/upload")
    @PreAuthorize("hasRole('user')")
    public ApiResult upload(MultipartFile file,@RequestParam String info){
        coursewareService.upload(file,info);
        return ApiResult.success();
    }

    @PostMapping("/add")
    @PreAuthorize("hasRole('user')")
    public ApiResult add(MultipartFile file,@RequestParam String info){
        coursewareService.upload(file,info);
        return ApiResult.success();
    }

    @GetMapping ("/download/{id}")
    @PreAuthorize("hasRole('user')")
    public ResponseEntity download(@PathVariable Integer id) throws IOException {
        byte[] bytes = coursewareService.download(id);
        Courseware courseware = coursewareService.findById(id);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment",courseware.getName());
        eventPublisher.publishEvent(new CoursewareDownloadEvent(this,id));
        return new ResponseEntity<>(bytes,headers, HttpStatus.OK);
    }


}
